package com.cloud.demo.models.bus.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.demo.common.cache.cachekey.bus.BusOrderCacheKeyBuild;
import com.cloud.demo.common.enums.ProductProgressEnum;
import com.cloud.demo.common.enums.ResultEnum;
import com.cloud.demo.common.web.exception.BusException;
import com.cloud.demo.models.bus.domian.BusOrder;
import com.cloud.demo.models.bus.domian.BusOrderDetailed;
import com.cloud.demo.models.bus.domian.BusOrderHistory;
import com.cloud.demo.models.bus.mapper.BusOrderMapper;
import com.cloud.demo.models.bus.qo.OrderQo;
import com.cloud.demo.models.bus.service.BusHistoryService;
import com.cloud.demo.models.bus.service.BusOrderService;
import com.cloud.demo.models.sys.service.SysDeptService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Service
public class BusOrderServiceImpl extends ServiceImpl<BusOrderMapper, BusOrder> implements BusOrderService {

    @Resource
    private BusOrderMapper busOrderMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private SysDeptService sysDeptService;
    @Resource
    private BusHistoryService busHistoryService;

    @Override
    public void updateOrder(BusOrderDetailed busOrderList) {
        List<BusOrder> busOrders = busOrderList.getBusOrderList();
        BusOrder busOrder = busOrders.get(1);
        busOrders.forEach(b->{
            LambdaQueryWrapper<BusOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BusOrder::getOrderId,b.getOrderId())
                    .eq(BusOrder::getId,b.getId());
            busOrderMapper.update(b,wrapper);
        });


        BusOrderHistory history = historySet(busOrderList);

        //history插入历史
        busHistoryService.insertHistory(history,"update");

    }

    private BusOrderHistory historySet(BusOrderDetailed busOrderList) {
        BusOrderHistory history = new BusOrderHistory();
        history.setBrand(busOrderList.getBrand());
        history.setOrderId(Integer.valueOf(busOrderList.getOrderId()));
        history.setClientId(busOrderList.getClineId());
        history.setOperation(1L);
        history.setOperatorId(busOrderList.getSaleId());
        history.setDepartmentId(busOrderList.getDeptId().intValue());
        return history;
    }


    @Override
    public void insetOrder(BusOrderDetailed busOrderDetailed, String orderNum) {
        //查看Redis订单号是否已经存在，如果存在，更新订单号;然后再插入

        String key = new BusOrderCacheKeyBuild().getKey(orderNum);
        String s = stringRedisTemplate.opsForValue().get(key);
        List<BusOrder> busOrderList = busOrderDetailed.getBusOrderList();
        if (s!=null ) {
            String on = orderNum();//刷新单号
            throw new BusException(ResultEnum.ORDER_EXIST,on);
        }
        if (CollectionUtil.isEmpty(busOrderList)) {
            throw new BusException(ResultEnum.ORDER_IS_NULL,null);
        }

        QueryWrapper<BusOrder> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(BusOrder::getOrderId,orderNum);
        boolean exists = busOrderMapper.exists(wrapper);
        if (exists) {
            throw new BusException(ResultEnum.ORDER_EXIST,null);
        }
        busOrderList.forEach(BusOrder -> {
            String orderConfirm = String.valueOf(ProductProgressEnum.PROCESS_STATE_ORDER_CONFIRM);
            BusOrder.setProcessState(orderConfirm);
            BusOrder.setCreateTime(new Date());
            BusOrder.setIsComplete(0);
            BusOrder.setOrderId(orderNum);
            //  stringRedisTemplate.opsForHash().put(key,BusOrder.getProductModel(), BusOrder);

            busOrderMapper.insert(BusOrder);
        });
        //历史记录
        BusOrderHistory history = historySet(busOrderDetailed);
        busHistoryService.insertHistory(history,"insert");




    }

    @Override
    public String orderNum() {
        /*LambdaQueryWrapper<BusOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(BusOrder::getId);
        List<BusOrder> busOrders = busOrderMapper.selectList(wrapper);*/
        String likeKey = new BusOrderCacheKeyBuild().getKey("*");
        Set<String> keys = stringRedisTemplate.keys(likeKey);
        List<Integer> orderNums = new ArrayList<>();
        for (String key : keys) {
            int index = key.lastIndexOf(":");
            String substring = key.substring(index+9);//+9获取yyyymmdd后四位号码0000
            orderNums.add(Integer.valueOf(substring));

        }

        Comparator<Integer> comparator = (o1, o2) -> {
            return o1 -  o2;
        };

        Integer max = Collections.max(orderNums, comparator);
        //yyyymmdd0001   +1 ==0000 则订单已满 请联系管理员处理
        int orderNum = max + 1;
        String num  = null;
        if (orderNum>=10000) {
            throw new BusException(ResultEnum.ORDER_FULL,null);
        }else {
             num = String.format("%04d",orderNum);

        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = simpleDateFormat.format(new Date());
        return date + num;
    }

    @Override
    public PageInfo<BusOrderDetailed> pageList(OrderQo qo) {
        //通过不为空的条件查询所有订单
        PageHelper.startPage(qo.getCurrentPage(),qo.getLimit());
        List<BusOrderDetailed> orderDetaileds = busOrderMapper.selectOrderDetailed(qo);
        orderDetaileds.forEach(o->{
            LambdaQueryWrapper<BusOrder> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(BusOrder::getOrderId,o.getOrderId());
            o.setBusOrderList(busOrderMapper.selectList(wrapper));
        });


        return new PageInfo<>(orderDetaileds);

    }
}




